<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" v-show="showSearch" label-width="100px">
      <el-row>
        <el-card shadow="always" style="margin-bottom: 10px;" v-if="false">
          <el-radio-group v-model="queryParams.params.query_type" size="mini">
            <el-radio-button label="5">个人排行汇总</el-radio-button>
            <el-radio-button label="4">个人排行明细</el-radio-button>
          </el-radio-group>
        </el-card>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="日期" prop="logDate2">
            <el-date-picker v-model="queryParams.logDate2" type="daterange" :picker-options="pickerOptions"
                            range-separator="至" start-placeholder="日期" end-placeholder="结束日期" align="right"
                            value-format="yyyy-MM-dd"
                            format="yyyy-MM-dd" style="width: 100%;">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="角色">
            <el-select v-model="queryParams.roleKey" filterable placeholder="请选择">
              <el-option label="部长" value="4"></el-option>
              <el-option label="顾问" value="5"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="部门归属" prop="orgId">
            <treeselect v-model="queryParams.orgId" :options="deptOptions" :show-count="true" placeholder="请选择部门归属"
                        :default-expand-level="4"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="顾问" prop="empId">
            <el-select v-model="queryParams.empId" placeholder="顾问" clearable filterable multiple>
              <el-option v-for="user in sysUsersList" :key="user.userId" :label="user.nickName" :value="user.userId"/>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <template v-if="queryParams.params.query_type == 4 ">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">录入今天日志</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="el-icon-plus" size="mini" @click="handleAddYes">补录昨天日志</el-button>
        </el-col>
      </template>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="businesslogList" @selection-change="handleSelectionChange" show-summary :summary-method="getSummaries">
      <el-table-column type="selection" width="55" align="center"/>
      <template v-if="queryParams.params.query_type == 4 || queryParams.params.query_type == 5">
        <el-table-column v-if="queryParams.params.query_type == 4" label="日期" align="center" prop="logDate"/>
        <el-table-column label="顾问姓名" align="center" prop="empName"/>
        <el-table-column label="部门归属" align="center" prop="orgId">
          <template slot-scope="scope">
            {{ getDeptByOrgId(scope.row.orgId) }}
          </template>
        </el-table-column>
        <template v-if="queryParams.params.query_type == 4">
          <el-table-column label="今日上门数" align="center" prop="todayVisitCount">
            <template slot-scope="scope">
              <span class="report_span1" @click="custleveldataDetails(scope.row.emp_id,scope.row.todayVisitCustids)">{{ scope.row.todayVisitCount }}</span>
            </template>
          </el-table-column>
          <el-table-column label="今日签约数" align="center" prop="todaySignedCount">
            <template slot-scope="scope">
              <span class="report_span2" @click="custleveldataDetails(scope.row.emp_id,scope.row.todaySignedCustids)">{{ scope.row.todaySignedCount }}</span>
            </template>
          </el-table-column>
          <el-table-column label="今日进件数" align="center" prop="todayIncomingCount"></el-table-column>
          <el-table-column label="明日预计上门数" align="center" prop="tomorrowVisitCount"></el-table-column>
          <el-table-column label="今日新增好友数" align="center" prop="wechatFriendsTodayadd"></el-table-column>
        </template>
        <template v-if="queryParams.params.query_type == 5">
          <el-table-column label="上门" align="center" prop="todayVisitCount">
          </el-table-column>
          <el-table-column label="签约" align="center" prop="todaySignedCount">
          </el-table-column>
          <el-table-column label="进件" align="center" prop="todayIncomingCount">
          </el-table-column>
          <el-table-column label="新增好友数" align="center" prop="wechatFriendsTodayadd">
          </el-table-column>
        </template>

        <el-table-column label="今日进件小贷客户数" align="center" prop="todayIntroductionCount"></el-table-column>
        <el-table-column label="今日小贷担保人上门数" align="center" prop="todayIntroductionVisit"></el-table-column>
        <el-table-column label="扫码签约数" align="center" prop="introductionSignedCount"></el-table-column>
        <el-table-column label="扫码签约率" align="center" prop="introductionSignedRate"></el-table-column>
        <el-table-column label="短信跟进客户数" align="center" prop="todaySmsfollowCount"></el-table-column>
        <el-table-column label="签约率%" align="center" prop="todaySignedRate"></el-table-column>
        <el-table-column label="通时(分)" align="center" prop="todayCallTime"></el-table-column>
        <template
          v-if="resMap.company_leader == 1 || resMap.sub_leader == 1 || resMap.area_leader == 1 || resMap.depart_leader == 1 || resMap.is_xingzheng == 1">
          <el-table-column label="帮谈客户次数" align="center" prop="todayTalkCount"></el-table-column>
          <el-table-column label="分配客户次数/总量" align="center" prop="todayDistributeCount"></el-table-column>
          <el-table-column label="加入必跟进次数/总量" align="center" prop="todayAddmustCount"></el-table-column>
        </template>
      </template>

      <template v-else>
        <el-table-column label="部门归属" align="center" prop="orgId">
          <template slot-scope="scope">
            {{ getDeptByOrgId(scope.row.orgId) }}
          </template>
        </el-table-column>
        <el-table-column label="上门" align="center" prop="todayVisitCount"/>
        <el-table-column label="人均上门" align="center" prop="todayVisitCount"/>
        <el-table-column label="签约" align="center" prop="todaySignedCount"/>
        <el-table-column label="人均签约" align="center" prop="todaySignedCountRate"/>
        <el-table-column label="进件小贷客户数" align="center" prop="todayIntroductionCount"/>
        <el-table-column label="人均小贷客户数" align="center" prop="todayIntroductionCountRate"/>
        <el-table-column label="小贷担保人上门数" align="center" prop="todayIntroductionVisit"/>
        <el-table-column label="人均小贷担保人上门数" align="center" prop="todayIntroductionVisitRate"/>
        <el-table-column label="扫码签约数" align="center" prop="introductionSignedCount"/>
        <el-table-column label="扫码签约率%" align="center" prop="introductionSignedCountRate"/>
      </template>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width"
                       v-show="queryParams.params.query_type == 4"
                       prop="operation">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['crmsys:businesslog:edit']">修改
          </el-button>
        </template>
      </el-table-column>

      <!-- 查看客户列表 -->
      <el-dialog :title="title" :visible.sync="open" class="dialogCust" width="96%" :fullscreen="modalverbs" append-to-body :modalverbs="modalverbs" :destroy-on-close="modalverbs">
        <cust-info-list :form.sync="form"></cust-info-list>
      </el-dialog>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

  </div>
</template>

<script>
import {
  listBusinesslog,
  getBusinesslog,
  delBusinesslog,
  addBusinesslog,
  updateBusinesslog
} from "@/api/crmsys/businesslog";
import {
  getAllDeptandUsers,
  getPublicCustSet
} from "@/api/crmsys/custinfo/custinfo";

import Treeselect from "@riophae/vue-treeselect";
import {deptTreeSelect, childrenAlldeptTree} from "@/api/system/user";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import CustInfoList from "@/components/crmSys/custInfoList";
import modal from "@/plugins/modal";

export default {
  name: "Businesslog",
  components: {Treeselect, CustInfoList},
  data() {
    return {
      modalverbs:false,
      title: '客户列表',
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 日志报表表格数据
      businesslogList: [],
      resMap: {
        right_type: null,
        company_id: null,
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      // 部门归属树选项
      deptOptions: [],
      sysUsersList: [],
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 1000,
        roleKey: null,
        empId: null,
        orgId: null,
        params: {
          query_type: 4
        },
        logDate2: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        empId: [
          {required: true, message: "顾问编号不能为空", trigger: "blur"}
        ],
        orgId: [
          {required: true, message: "部门归属不能为空", trigger: "blur"}
        ],
        empName: [
          {required: true, message: "顾问姓名不能为空", trigger: "blur"}
        ],
        wechatFriendsTotal: [
          {required: true, message: "微信好友总数不能为空", trigger: "blur"}
        ],
        wechatFriendsTodayadd: [
          {required: true, message: "微信好友今日新增数量不能为空", trigger: "blur"}
        ],
        todayNewcustCount: [
          {required: true, message: "今日新开发客户数量不能为空", trigger: "blur"}
        ],
        todayIntroductionCount: [
          {required: true, message: "今日扫码次数不能为空", trigger: "blur"}
        ],
        todaySmsfollowCount: [
          {required: true, message: "今日短信跟进客户次数不能为空", trigger: "blur"}
        ],
        todayCallTime: [
          {required: true, message: "今日通时不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getPublicCustSet();
    this.queryParams.logDate2 = [this.getDate("yesterday"), this.getDate()];
    this.getList();
    this.getDeptTree();
    this.getDeptAndUsers();
  },
  methods: {
    /** 总计 */
    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (column.property !== 'logDate' && column.property !== 'empName' && column.property !== 'orgId'  && column.property !== 'todaySignedRate' && column.property !== 'operation') {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
        }
        sums[index];
      });
      return sums;
    },
    /** 查询日志报表列表 */
    getList() {
      this.loading = true;
      //时间函数
      this.addDateRange(this.queryParams, this.queryParams.logDate2, "logDate");
      this.queryParams.params.roleKey = this.queryParams.roleKey;

      listBusinesslog(this.queryParams).then(response => {
        this.businesslogList = response.list.rows;
        this.total = response.list.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    getDate(type) {
      let currentDate = new Date();
      if (type == "yesterday") {
        currentDate = new Date(currentDate.getTime() - 24 * 60 * 60 * 1000); // 减去一天的毫秒数
      }
      let year = currentDate.getFullYear();
      let month = currentDate.getMonth() + 1; // 月份是从0开始的，所以要加1
      let day = currentDate.getDate();
      if (month < 10) {
        month = "0" + month;
      }
      if (day < 10) {
        day = "0" + day;
      }
      return year + "-" + month + "-" + day;
    },

    /** 查询部门归属下拉树结构 */
    getDeptTree() {
      var dept = {deptId: this.$store.state.user.deptid}
      childrenAlldeptTree(dept).then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 获取部门归属和人员信息 */
    getDeptAndUsers() {
      getAllDeptandUsers().then((response) => {
        this.sysUsersList = response.data.sysUsersList;
      });
    },
    getPublicCustSet() {
      getPublicCustSet().then(response => {
        this.resMap = response.data;
      });
    },
    custleveldataDetails(userId, custids) {
      //查询明细数据
      let inparams={};
      inparams.oldUserId=userId;
      inparams.params={};
      inparams.params.ids=custids;
      inparams.params.isCheckDept=1;
      inparams.pageNum=1;
      inparams.pageSize=10;
      this.$set(this.$data, 'form', inparams);
      this.open=true;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        empId: null,
        orgId: null,
        empName: null,
        todayVisitCount: null,
        todayVisitCustids: null,
        todayVisitContent: null,
        todaySignedCount: null,
        todaySignedCustids: null,
        todaySignedContent: null,
        todayIncomingCount: null,
        todayIncomingCustids: null,
        todayIncomingContent: null,
        tomorrowVisitCount: null,
        tomorrowVisitCustids: null,
        tomorrowVisitContent: null,
        wechatFriendsTotal: null,
        wechatFriendsTodayadd: null,
        todayNewcustCount: null,
        todayIntroductionCount: null,
        todaySmsfollowCount: null,
        todayCallTime: null,
        todayIncomingTeam: null,
        todayMustcustTeam: null,
        logDate: null,
        createTime: null,
        updateTime: null,
        remark: null,
        todayIntroductionVisit: null,
        todaySignedRate: null,
        todayTalkCount: null,
        todayDistributeCount: null,
        todayDistributeDetail: null,
        todayAddmustCount: null,
        todayAddmustDetail: null,
        introductionSignedCount: null,
        introductionSignedRate: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (this.queryParams.logDate2 == null) {
        this.$message.error("日期不能为空");
        return;
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // this.handleQuery();
      console.log(this.queryParams);
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增今天日志 */
    handleAdd() {
      const params = {
        id: "",
        type: "today",
        queryParams: this.queryParams,
        pageNum: this.queryParams.pageNum,
        form: this.form,
        routePath: this.$route.path
      };
      this.$tab.openPage(
        "新增日志信息",
        "/report/businesslog/logedit/info/",
        params
      );


    },
    /** 新增昨天日志 */
    handleAddYes() {
      const params = {
        id: "",
        type: "yesterday",
        queryParams: this.queryParams,
        pageNum: this.queryParams.pageNum,
        form: this.form,
        routePath: this.$route.path
      };
      this.$tab.openPage(
        "新增日志信息",
        "/report/businesslog/logedit/info/",
        params
      );


    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids

      const params = {
        id: id,
        type: "yesterday",
        queryParams: this.queryParams,
        pageNum: this.queryParams.pageNum,
        form: this.form,
        routePath: this.$route.path
      };
      this.$tab.openPage(
        "修改日志信息",
        "/report/businesslog/logedit/info/",
        params
      );
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateBusinesslog(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBusinesslog(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除日志报表编号为"' + ids + '"的数据项？').then(function () {
        return delBusinesslog(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('crmsys/businesslog/export', {
        ...this.queryParams
      }, `businesslog_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style lang="scss" scoped>
@import '@/assets/styles/command.scss';
.report_span1 {
  color: blue;
  cursor: pointer;
}

.report_span2 {
  color: rgb(231, 62, 146);
  cursor: pointer;
}
</style>
